package com.bckj.fastboot.core.web.repeat.strategy;

import com.bckj.fastboot.core.redis.RedisOps;
import com.bckj.fastboot.core.web.repeat.RepeatSubmit;
import com.bckj.fastboot.core.web.repeat.RepeatSubmitTypes;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class SameTokenRepeatSubmitStrategy implements RepeatSubmitStrategy {

    private final RedisOps redisOps;

    @Override
    public String getType() {
        return RepeatSubmitTypes.SAME_TOKEN;
    }

    @Override
    public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) {
        boolean isRepeatSubmit = false;
        String token = request.getParameter("retoken");
        if (!StringUtils.hasText(token) || redisOps.get(getKey(request, token)) != null) {
            isRepeatSubmit = true;
        } else {
            redisOps.set(getKey(request, token), true, annotation.interval(), TimeUnit.MILLISECONDS);
        }
        return isRepeatSubmit;
    }

    private String getKey(HttpServletRequest request, String token) {
        return "resubmit:" + request.getRequestURI().replace("/", "") + ":" + token;
    }
}
